var t;
var liIndex =  - 1;
var oldIndex =  - 1;

function resetIndex() {
    liIndex =  - 1;
}

function keyEvent(e) {
    if (window.event) {
        e = window.event;
    }

    var b = (window.event) ? window.event.keyCode : e.keyCode;
    var rt = 13;
    var au = 38;
    var ad = 40;
    var pu = 33;
    var pd = 34;
    var ul = document.getElementById("as_ul");

    switch (b) {
        case au:
            if (!ul) {
                return false;
            }

            if (liIndex >  - 1)
                ul.childNodes[liIndex].className = "";

            liIndex = liIndex - 1 <=  - 1 ? ul.childNodes.length - 1 : liIndex - 1;
            ul.childNodes[liIndex].className = "as_highlight";
            var c1 = ul.childNodes[liIndex];
            c1.onclick();
            break;
        case ad:
            if (!ul) {
                return false;
            }

            if (liIndex >  - 1)
                ul.childNodes[liIndex].className = "";

            liIndex = liIndex + 1 >= ul.childNodes.length ? 0 : liIndex + 1;
            ul.childNodes[liIndex].className = "as_highlight";
            var c2 = ul.childNodes[liIndex];
            c2.onclick();
            break;
        case rt:
            hideLocationSearchResults();
            break;
        default :
            searchLocations();
    }
}

function showLocationSearchResults() {
    var srh = window.document.getElementById('searchResultsHtml');
    var sra = window.document.getElementById('searchResultsArea');
    sra.innerHTML = srh.value;
    sra.style = "width: 400px; display: block;"
}

function hideLocationSearchResults() {
    var sra = window.document.getElementById('searchResultsArea');
    sra.innerHTML = "";
    sra.style = "width: 0px; display: none;"
}

var xhr;

function initXHR() {
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
}

function searchLocations() {
    resetIndex();
    window.clearTimeout(t);
    t = window.setTimeout("searchForLocations();", 500);
}

function searchForLocations() {
    var query = document.getElementById('locSearchInput').value;
    var sll = gmap.getCenter();

    var url = "/locationSearch?q=" + encodeURIComponent(query) + "&sll=" + encodeURIComponent(sll);
    sendRequest(url, processAjaxCall);
}

function sendRequest(url, handler) {
    initXHR();
    xhr.onreadystatechange = handler;
    xhr.open("GET", url, true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    xhr.send(null);
}

function processAjaxCall() {
    if (xhr.readyState == 4) {
        if (xhr.status == 200) {
            var sra = window.document.getElementById('searchResultsArea');
            sra.innerHTML = xhr.responseText;
            sra.style = "width: 400px; display: block;"
        }
    }
}